<!-- src\components\dialog\AuthDialog.vue -->
<template>
  <el-dialog
    v-model="dialogVisible"
    :width="dialogWidth"
    :before-close="handleClose"
    custom-class="auth-dialog"
  >
    <template #header>
      <div class="dialog-header">
        <div class="welcome-text">欢迎进入智慧农业机器管理系统</div>
        <div class="tab-buttons">
          <el-button type="primary" text @click="setLoginMethod('password')" :class="{ active: loginMethod === 'password' && mode === 'login' }">账号密码</el-button>
          <el-button type="primary" text @click="setLoginMethod('email')" :class="{ active: loginMethod === 'email' && mode === 'login' }">邮箱登录</el-button>
          <el-button type="primary" text @click="setLoginMethod('wechat')" :class="{ active: loginMethod === 'wechat' && mode === 'login' }">微信登录</el-button>
          <el-button type="primary" text @click="setMode('register')" :class="{ active: mode === 'register' }">注册</el-button>
        </div>
      </div>
    </template>

    <div class="form-container">

      <!-- 密码登录 -->
      <el-form v-if="loginMethod === 'password' && mode === 'login'" :model="passwordForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="passwordForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="passwordForm.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <!-- 邮箱登录 -->
      <el-form v-if="loginMethod === 'email' && mode === 'login'" :model="emailForm" label-width="100px">
        <el-form-item label="邮箱">
          <el-input v-model="emailForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="emailForm.code" autocomplete="off">
            <template #append>
              <el-button @click="sendEmailCode" :disabled="emailCountdown > 0">
                {{ emailCountdown > 0 ? `${emailCountdown}s` : '发送验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 微信登录 -->
      <div v-if="loginMethod === 'wechat' && mode === 'login'" class="wechat-qr">
        <img v-if="wechatQrUrl" :src="wechatQrUrl" alt="微信二维码" />
        <p>请使用微信扫描二维码登录</p>
      </div>

      <!-- 注册表单 -->
      <el-form v-if="mode === 'register'" :model="registerForm" label-width="120px" ref="registerFormRef" :rules="registerRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="registerForm.realName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="registerForm.code" autocomplete="off">
            <template #append>
              <el-button @click="sendEmailCodeForRegister" :disabled="emailCountdown > 0">
                {{ emailCountdown > 0 ? `${emailCountdown}s` : '发送验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="用户身份" prop="role">
          <el-select v-model="registerForm.role" placeholder="请选择身份">
            <el-option label="农民" value="FARMER"></el-option>
            <el-option label="管理人员" value="MANAGER"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="农业领域" prop="agriculturalField" v-if="registerForm.role === 'FARMER'">
          <el-radio-group v-model="registerForm.agriculturalField">
            <div v-for="group in agriculturalFields" :key="group.title" class="field-group">
              <h3>{{ group.title }}</h3>
              <div v-for="option in group.options" :key="option.value" class="field-option">
                <div class="option-row">
                  <el-radio :value="option.value">{{ option.label }}</el-radio>
                  <span class="description">{{ option.description }}</span>
                </div>
              </div>
            </div>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="农业机器" prop="agriculturalMachines" v-if="registerForm.role === 'FARMER'">
          <el-checkbox-group v-model="registerForm.agriculturalMachines">
            <div v-for="group in agriculturalMachines" :key="group.title" class="machine-group">
              <h3>{{ group.title }}</h3>
              <div v-for="option in group.options" :key="option.value" class="machine-option">
                <div class="option-row">
                  <el-checkbox :value="option.value">{{ option.label }}</el-checkbox>
                  <span class="description">{{ option.description }}</span>
                </div>
              </div>
            </div>
          </el-checkbox-group>
        </el-form-item>

      </el-form>
    </div>

    <div class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleLogin" v-if="mode === 'login'">确认登录</el-button>
      <el-button type="primary" @click="handleRegister" v-if="mode === 'register'">确认注册</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import axios from '../../plugins/axios';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useAgriculturalDataStore } from '@/stores/agriculturalData';

interface PasswordForm {
  username: string;
  password: string;
}

interface EmailForm {
  email: string;
  code: string;
}

interface RegisterForm {
  username: string;
  password: string;
  realName: string;
  email: string;
  code: string;
  role: string;
  agriculturalField: string;
  agriculturalMachines: string[];
}

const WECHAT_APP_ID = 'wxb95530a7015b5532';
const WECHAT_REDIRECT_URI = 'https://8.130.135.229:8082/wechat/callback';

const props = defineProps<{
  visible: boolean;
  onDialogClose: () => void;
}>();

const dialogVisible = ref<boolean>(props.visible);
const mode = ref<'login' | 'register'>('login');
const loginMethod = ref<'password' | 'email' | 'wechat'>('password');

const passwordForm = ref<PasswordForm>({ username: '', password: '' });
const emailForm = ref<EmailForm>({ email: '', code: '' });
const registerForm = ref<RegisterForm>({
  username: '',
  password: '',
  realName: '',
  email: '',
  code: '',
  role: '',
  agriculturalField: '',
  agriculturalMachines: [],
});

const registerFormRef = ref<InstanceType<typeof ElForm>>();

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }], // 新增
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择用户身份', trigger: 'change' }],
  agriculturalField: [
    { required: true, message: '请选择农业领域', trigger: 'change', validator: (rule, value, callback) => {
      if (registerForm.value.role === 'FARMER' && !value) {
        callback(new Error('请选择农业领域'));
      } else {
        callback();
      }
    }},
  ],
};

const wechatQrUrl = ref<string>('');
const emailCountdown = ref<number>(0);

const setMode = (newMode: 'login' | 'register') => {
  mode.value = newMode;
  if (newMode === 'register') loginMethod.value = '';
};

const setLoginMethod = (method: 'password' | 'email' | 'wechat') => {
  mode.value = 'login';
  loginMethod.value = method;
};

const userStore = useUserStore();
const router = useRouter();

const agriculturalDataStore = useAgriculturalDataStore();
const agriculturalFields = agriculturalDataStore.getAgriculturalFields;
const agriculturalMachines = agriculturalDataStore.getAgriculturalMachines;

const handleLoginSuccess = (userData) => {
  userStore.setUser(userData);
  dialogVisible.value = false;
  props.onDialogClose();
  router.push('/user/profile');
};

const sendEmailCode = async () => {
  if (!emailForm.value.email) {
    ElMessage.error('请先输入邮箱');
    return;
  }
  try {
    const response = await axios.post('/user/send-email-code', { email: emailForm.value.email });
    if (response.data.code === 200) {
      ElMessage.success('验证码已发送');
      emailCountdown.value = 60;
      const timer = setInterval(() => {
        emailCountdown.value--;
        if (emailCountdown.value <= 0) clearInterval(timer);
      }, 1000);
    } else {
      ElMessage.error(response.data.message || '发送失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  }
};

const sendEmailCodeForRegister = async () => {
  if (!registerForm.value.email) {
    ElMessage.error('请先输入邮箱');
    return;
  }
  try {
    const response = await axios.post('/user/send-email-code', { email: registerForm.value.email });
    if (response.data.code === 200) {
      ElMessage.success('验证码已发送');
      emailCountdown.value = 60;
      const timer = setInterval(() => {
        emailCountdown.value--;
        if (emailCountdown.value <= 0) clearInterval(timer);
      }, 1000);
    } else {
      ElMessage.error(response.data.message || '发送失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  }
};

const generateWechatQr = () => {
  const state = Math.random().toString(36).substring(2);
  const qrUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${WECHAT_APP_ID}&redirect_uri=${encodeURIComponent(
    WECHAT_REDIRECT_URI
  )}&response_type=code&scope=snsapi_login&state=${state}`;
  wechatQrUrl.value = qrUrl;
  window.addEventListener('message', mode.value === 'register' ? handleWechatBindCallback : handleWechatLoginCallback);
};

const bindWechat = () => {
  generateWechatQr();
};

const handleWechatLoginCallback = async (event) => {
  if (event.data && event.data.id) {
    ElMessage.success('微信登录成功');
    handleLoginSuccess(event.data);
    window.removeEventListener('message', handleWechatLoginCallback);
  }
};

const handleWechatBindCallback = async (event) => {
  if (event.data && event.data.wechatOpenId) {
    // registerForm.value.wechatOpenId = event.data.wechatOpenId;
    ElMessage.success('微信绑定成功');
    window.removeEventListener('message', handleWechatBindCallback);
  }
};

const handleLogin = async () => {
  let response;
  try {
    if (loginMethod.value === 'password') {
      response = await axios.post('/user/login/password', passwordForm.value);
    } else if (loginMethod.value === 'email') {
      response = await axios.post('/user/login/email', emailForm.value);
    }
    if (response.data.code === 200) {
      ElMessage.success('登录成功');
      handleLoginSuccess(response.data.data);
    } else {
      ElMessage.error(response.data.message || '登录失败');
    }
  } catch (error) {
    ElMessage.error(response.data.message || '网络错误，请稍后重试');
  }
};

const handleRegister = async () => {
  registerFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.post('/user/register', registerForm.value);
        if (response.data.code === 200) {
          ElMessage.success('注册成功，请登录');
          dialogVisible.value = false;
          props.onDialogClose();
        } else {
          ElMessage.error(response.data.message || '注册失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
        console.log(error)
      }
    }
  });
};

watch(() => loginMethod.value, (newVal) => {
  if (newVal === 'wechat' && mode.value === 'login') {
    generateWechatQr();
  }
});

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    emailCountdown.value = 0;
  }
});

const dialogWidth = computed(() => {
  return mode.value === 'register' ? '1100px' : '700px';
});

const handleClose = (done: () => void) => {
  done();
};

</script>

<style scoped>
.auth-dialog {
  border-radius: 8px;
}

.dialog-header {
  text-align: center;
  padding-bottom: 20px;
}

.welcome-text {
  font-size: 24px;
  color: #606266;
  margin: 30px 0 50px 20px;
  font-weight: 500;
  text-align: center;
}

.tab-buttons {
  display: flex;
  justify-content: center;
  gap: 30px;
  padding-left: 50px;
}

.tab-buttons .el-button {
  font-size: 18px;
  padding: 10px 20px;
}

.el-button.active {
  border-bottom: 3px solid #409eff;
  color: #409eff;
}

.form-container {
  padding: 0 150px 20px 150px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
}

.wechat-qr {
  text-align: center;
}

.wechat-qr img {
  width: 200px;
  height: 200px;
}

.machine-group {
  margin-top: 10px;
  margin-bottom: 10px;
}

.field-group h3, .machine-group h3 {
  font-size: 16px;
  color: #303133;
}

.field-group h3 {
  margin: 0 10px 10px 0;
}
.machine-group h3 {
  margin: 20px 10px 20px 0;
}

.field-option {
  margin-left: 20px;
}

.machine-option {
  margin-left: 20px;
  margin-bottom: 8px;
}

.description {
  font-size: 12px;
  color: #909399;
  margin: 5px 0 0 25px;
}

.auth-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 0;
  border-bottom: none;
}

.auth-dialog :deep(.el-dialog__body) {
  padding: 0 20px;
}
</style>